<template>
  <div>
    <el-form :model="sysRoleSearch" inline ref="searchFormRef">
      <el-form-item label="关键词" prop="keywords">
        <el-input v-model="sysRoleSearch.keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="getSysRoleList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Refresh" type="primary" @click="resetSearch(searchFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button :icon="Plus" size="small" type="primary" @click="openAddSysRole">新增</el-button>
    <el-table :data="rolePage.list" style="width: 100%" row-key="roleId" v-loading="loading">
      <el-table-column prop="roleId" label="编号"/>
      <el-table-column prop="roleName" label="名称"/>
      <el-table-column prop="roleCode" label="标识"/>
      <el-table-column prop="createTime" label="创建时间" >
        <template #default="scope">
          {{ $timeFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          {{ scope.row.status === 0 ? "启用" : "禁用" }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="modifySysRole(scope.row)" :icon="EditPen" size="small" type="warning"
                     :disabled="scope.row.roleCode==='admin'">修改
          </el-button>
          <el-divider direction="vertical"/>
          <el-button @click="deleteSysRole(scope.row)" :icon="Delete" size="small" type="danger"
                     :disabled="scope.row.roleCode==='admin'">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="sysRoleSearch.pageNum"
        v-model:page-size="sysRoleSearch.pageSize"
        layout=" prev, pager, next"
        :total="total"
    />
    <el-dialog
        v-model="dialogFormVisible"
        :title="dialogIsAdd ? '新增' : '修改'"
        width="600"
        draggable
        @close="roleFormReset"
    >
      <el-form :model="sysRoleCreate" label-width="100" :rules="rules" ref="ruleFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="sysRoleCreate.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色标识" prop="roleCode">
          <el-input v-model="sysRoleCreate.roleCode" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="权限分配" prop="menuIds">
          <div style="width: 100%">
            <el-checkbox v-model="sysPermissionTreeOption.isCheckedAll" label="全选"/>
            <el-checkbox v-model="sysPermissionTreeOption.isExpandAll" label="全部展开"/>
            <el-tree
                ref="treeRef"
                :data="sysPermissionTreeOption.data"
                node-key="menuId"
                check-strictly
                :default-expand-all="sysPermissionTreeOption.isExpandAll"
                :props="sysPermissionTreeOption.props"
                :default-checked-keys="sysRoleCreate.menuIds"
                show-checkbox
                class="value"
            >
            </el-tree>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="sysRoleCreate.status">
            <el-radio :value="0">启动</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSysRole(ruleFormRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, ref, onMounted, watch} from "vue";
import {Plus, Search, Refresh, EditPen, Delete, ArrowDown} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox, ElTree} from "element-plus";
import {reqCreateRole, reqDeleteRoleById, reqGetRolePageList, reqUpdateRole} from "@/api/system/role.js";
import {reqGetMenuListByRoleId, reqGetMenuTreeList} from "@/api/system/menu.js";

let rolePage = reactive({
  list: [],
  total: 0,
  pageNum: 1
})
let sysRoleSearch = reactive({
  keyword: "",
  pageNum: 1,
  pageSize: 10,
});
let loading = ref(true);
const searchFormRef = ref();
let dialogIsAdd = ref(true);
let dialogFormVisible = ref(false);
const treeRef = ref()
let sysRoleCreate = reactive({
  roleId: null,
  roleName: "",
  roleCode: "",
  createTime: null,
  menuIds: [],
  status: 0
});
let sysPermissionTreeOption = reactive({
  data: [],
  props: {
    children: "children",
    label: "menuName",
  },
  isExpandAll: false,
  isCheckedAll: false,
})
let total = ref(0)
const ruleFormRef = ref();
let rules = reactive({
  roleName: [{required: true, message: "请输入角色名称", trigger: "blur"}],
  roleCode: [{required: true, message: "请输入角色标识", trigger: "blur"}],
  createBy: [{required: true, message: "请输入创建人", trigger: "blur"}],
});

function resetSearch(formEl) {
  if (!formEl) return;
  formEl.resetFields();
}

let modifySysRole = async (role) => {
  Object.assign(sysRoleCreate, role)
  let res = await reqGetMenuTreeList()
  sysPermissionTreeOption.data = res.data
  let res2 = await reqGetMenuListByRoleId(role.roleId)
  if (Array.isArray(res2.data)) sysRoleCreate.menuIds = res2.data.map(item => item.menuId)
  dialogIsAdd.value = false;
  dialogFormVisible.value = true
}

let openAddSysRole = async () => {
  let res = await reqGetMenuTreeList()
  sysPermissionTreeOption.data = res.data
  dialogIsAdd.value = true; // 表示新增dialog
  dialogFormVisible.value = true; // 开启diaglog
}

let roleFormReset = () => {
  sysRoleCreate.roleId = null
  sysRoleCreate.roleName = ""
  sysRoleCreate.roleCode = ""
  sysRoleCreate.menuIds = []
  dialogIsAdd.value = true
}

function getSysRoleList() {
  return reqGetRolePageList(sysRoleSearch).then((res) => {
    Object.assign(rolePage, res.data)
  }).finally(() => {
    loading.value = false
  });
}

let saveSysRole = async (formEl) => {
  if (!formEl) return; // 表单校验
  //获取选中的权限id
  sysRoleCreate.menuIds = treeRef.value.getCheckedKeys(false)
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (dialogIsAdd.value) {
        reqCreateRole(sysRoleCreate)
      } else {
        reqUpdateRole(sysRoleCreate)
      }
    } else {
      console.log("error submit!", fields);
    }
  });
  await getSysRoleList()
  dialogFormVisible.value = false;
};

function deleteSysRole(role) {
  ElMessageBox.confirm("删除之后无法恢复，请确认是否删除？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeleteRoleById(role.roleId)
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！",
        });
      });
}

onMounted(() => {
  getSysRoleList();
});

watch([() => sysRoleSearch.pageSize, () => sysRoleSearch.pageNum], () => {
  getSysRoleList()
})
watch(() => sysPermissionTreeOption.isCheckedAll, () => {
  if (sysPermissionTreeOption.isCheckedAll) {
    treeRef.value.setCheckedKeys(sysPermissionTreeOption.data.map(item => item.menuId))
  } else {
    treeRef.value.setCheckedKeys([])
  }
})
</script>

<style scoped>
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.value {
  border: 1px solid var(--el-border-color);
}
</style>

